import React, { useState} from 'react'
import {View, Text, ScrollView} from '@tarojs/components'
import Taro from "@tarojs/taro"
import subjectStore, {findTopOfTree} from "../../store/subjectStore"
import './index.scss'


export default () => {
  const list = subjectStore.useStore(state => state.all);
  const current = subjectStore.useStore(state => state.current);
  const [select, setSelect] = useState<number>(() => {
    const top = findTopOfTree(list, current!!)
    return top?.id ?? 0
  });


  return (
    <View className='at-row'>
      <View className='at-col-3 left'>
        <ScrollView>
          {
            list.map(item => <LeftItem key={item.id} active={item.id === select} tetx={item.subjectName}
              onClick={() => {
                                         if (select === item.id) return
                                         setSelect(item.id)
                                       }
                                       }
            />)
          }
        </ScrollView>
      </View>
      <View className='at-col-9 wing-blank wing-space'>
        {
          list.find(item => item.id === select)?.children.map(item => {
            return (
              <View key={item.id}>
                <RightTitle text={item.subjectName} />
                <View className='right-box-container'>
                  {
                    item.children.map(ii => <View style={{padding: "8px 0 8px"}} key={ii.id}>
                      <View className={ii.id === current?.id ? 'right-box right-box-active' : 'right-box'} onClick={()=>{
                          if(ii.id !== current?.id){
                            subjectStore.dispatch("setCurrent",ii)
                          }
                          Taro.navigateBack()
                      }}
                      >
                        <Text>{ii.subjectName}</Text>
                      </View>
                    </View>)
                  }
                </View>
              </View>
            )
          })

        }
      </View>
    </View>
  )
}

const RightTitle = (props) => {
  return (
    <View className='right-title'>
      <Text>{props.text}</Text>
    </View>
  )
}

interface LeftItemProps {
  active: boolean,
  tetx: string,

  onClick()
}

const LeftItem = (props: LeftItemProps) => {
  let className = "left-item ";
  if (props.active) className = className + "left-item-active"
  return <View className={className} onClick={() => props.onClick()}>
    <Text>{props.tetx}</Text>
  </View>
}

